package com.ljm.file.recycle.time;

import com.ljm.file.properties.BucketType;
import com.ljm.file.recycle.entity.SysFileRecycle;
import com.ljm.file.recycle.mapper.SysFileRecycleMapper;
import com.ljm.file.recycle.service.ISysFileRecycleService;
import com.ljm.file.service.FileService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: ChenHuaMing
 * @Date: 2020/9/30 17:16
 * @Description: 清除垃圾文件 后续修改成第三方调度中心
 */
@Component
public class CleanGarbageFileTimer {
    @Resource
    private SysFileRecycleMapper sysFileRecycleMapper;
    @Resource
    private FileService fileService;

    @Scheduled(cron = "0 0 1 * * ?")
    public synchronized void cleanGarbageFile(){
        Long recycleFileCount = sysFileRecycleMapper.getRecycleFileCount();
        Long pageSize=100L;
        Long totalPage=recycleFileCount/pageSize+1;
        if(recycleFileCount>0){
            for (int i = 0; i < totalPage; i++) {
                List<SysFileRecycle> recycleFileData = sysFileRecycleMapper.getRecycleFileData(0L, pageSize);
                if(CollectionUtils.isNotEmpty(recycleFileData)){
                    recycleFileData.forEach(recycleFile->
                        fileService.deleteFile(recycleFile.getFileType()? BucketType.secrecyBucket: BucketType.secrecyBucket,
                                recycleFile.getStoragePath(),recycleFile.getOssFileId()+"."+recycleFile.getFileSuffix())
                    );
                }
                //删除文件回收站记录
                Set<Long> ids = recycleFileData.stream().map(temp -> temp.getId()).collect(Collectors.toSet());
                sysFileRecycleMapper.deleteFileRecycle(ids);
            }
        }
    }
}
